package com.example.smallmall.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.smallmall.common.api.CommonResult;
import com.example.smallmall.dto.GoodsParam;
import com.example.smallmall.dto.SpGoodsQueryParam;
import com.example.smallmall.entity.SpGoods;
import com.example.smallmall.entity.SpGoodsAttr;
import com.example.smallmall.entity.SpGoodsPics;
import com.example.smallmall.service.ISpGoodsAttrService;
import com.example.smallmall.service.ISpGoodsPicsService;
import com.example.smallmall.service.ISpGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author WSGL
 * @since 2020-07-20
 */
@Api(tags = "商品管理")
@RestController
@RequestMapping("/goods")
public class SpGoodsController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpGoodsController.class);
    @Resource
    private ISpGoodsService iSpGoodsService;
    @Resource
    private ISpGoodsPicsService iSpGoodsPicsService;
    @Resource
    private ISpGoodsAttrService iSpGoodsAttrService;

    @ApiOperation("商品列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Map<String, Object>> listGoods(SpGoodsQueryParam queryParam,
                                                       @RequestParam(value = "pageNum", defaultValue = "1") @ApiParam("页码") Integer pageNum,
                                                       @RequestParam(value = "pageSize")
                                                       @ApiParam("每页数量") Integer pageSize) {
        Map<String, Object> objectMap = iSpGoodsService.selectPage(queryParam, pageNum, pageSize);
        if (!objectMap.isEmpty()) {
            return CommonResult.success(objectMap);
        } else {
            return CommonResult.failed("查询失败");
        }
    }

    @ApiOperation("根据ID查询商品信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Map<String, Object>> listGoodsById(@PathVariable("id") Integer id) {
        SpGoods objects = iSpGoodsService.selectById(id);
        // PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(SpGoods.class);
        // Map<String, Object> map = BeanUtils.describe(person)
        Map<String, Object> objectMap;
        objectMap = BeanUtil.beanToMap(objects);
        Map<String, Object> objectMap1 = iSpGoodsPicsService.selectById(id);
        Map<String, Object> objectMap2 = iSpGoodsAttrService.selectById(id);
        objectMap.putAll(objectMap1);
        objectMap.putAll(objectMap2);
        return CommonResult.success(objectMap);
    }

    @ApiOperation("添加商品信息")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<GoodsParam> createGoods(@RequestBody GoodsParam goodsParam) {
        SpGoods spGoods = new SpGoods();
        SpGoodsPics spGoodsPics = new SpGoodsPics();
        List<SpGoodsAttr> spGoodsAttrs = new ArrayList<>();
        // 获取当前时间
        long time = DateUtil.date().getTime();
        int nowTimeInt = Math.toIntExact((time / 1000));
        // Bean对象拷贝
        BeanUtil.copyProperties(goodsParam, spGoods);
        spGoods.setAddTime(nowTimeInt);
        setGoodsCatIds(goodsParam, spGoods);
        boolean saveGoods = iSpGoodsService.save(spGoods);
        Integer goodsId = spGoods.getGoodsId();
        BeanUtil.copyProperties(goodsParam.getSpGoodsPics(), spGoodsPics);
        spGoodsPics.setGoodsId(goodsId);
        for (int i = 0; i < goodsParam.getSpGoodsAttrs().size(); i++) {
            SpGoodsAttr spGoodsAttr = new SpGoodsAttr();
            BeanUtil.copyProperties(goodsParam.getSpGoodsAttrs().get(i), spGoodsAttr);
            spGoodsAttr.setGoodsId(goodsId);
            spGoodsAttrs.add(spGoodsAttr);
        }
        boolean saveGoodsPics = iSpGoodsPicsService.save(spGoodsPics);
        boolean saveGoodsAttrBatch = iSpGoodsAttrService.saveBatch(spGoodsAttrs);
        if (saveGoods && saveGoodsPics && saveGoodsAttrBatch) {
            LOGGER.info("createGoods success: {}", goodsParam);
            return CommonResult.success(goodsParam);
        } else {
            LOGGER.info("createGoods failed: {}", goodsParam);
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("编辑商品信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public CommonResult<GoodsParam> updateGoods(@PathVariable("id") Integer id, @RequestBody GoodsParam goodsParam) {
        SpGoods spGoods = new SpGoods();
        SpGoodsPics spGoodsPics = new SpGoodsPics();
        List<SpGoodsAttr> spGoodsAttrs = new ArrayList<>();
        // 获取当前时间
        long time = DateUtil.date().getTime();
        int nowTimeInt = Math.toIntExact((time / 1000));
        // Bean对象拷贝
        BeanUtil.copyProperties(goodsParam, spGoods);
        spGoods.setUpdTime(nowTimeInt);
        setGoodsCatIds(goodsParam, spGoods);
        boolean updateGoods = iSpGoodsService.update(spGoods, new QueryWrapper<SpGoods>().lambda().eq(SpGoods::getGoodsId, id));
        BeanUtil.copyProperties(goodsParam.getSpGoodsPics(), spGoodsPics);
        boolean updateGoodsPics = iSpGoodsPicsService.update(spGoodsPics, new QueryWrapper<SpGoodsPics>().lambda().eq(SpGoodsPics::getGoodsId, id));
        for (int i = 0; i < goodsParam.getSpGoodsAttrs().size(); i++) {
            SpGoodsAttr spGoodsAttr = new SpGoodsAttr();
            BeanUtil.copyProperties(goodsParam.getSpGoodsAttrs().get(i), spGoodsAttr);
            spGoodsAttrs.add(spGoodsAttr);
        }
        boolean updateGoodsAttrBatch = iSpGoodsAttrService.saveOrUpdateBatch(spGoodsAttrs);
        if (updateGoods && updateGoodsPics && updateGoodsAttrBatch) {
            LOGGER.info("updateGoods success: {}", goodsParam);
            return CommonResult.success(goodsParam);
        } else {
            LOGGER.info("updateGoods failed: {}", goodsParam);
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("删除商品信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public CommonResult<Boolean> deleteGoods(@PathVariable("id") Integer id) {
        boolean removeGoods = iSpGoodsService.removeById(id);
        boolean removeGoodsPics = iSpGoodsPicsService.remove(new LambdaQueryWrapper<SpGoodsPics>().eq(SpGoodsPics::getGoodsId, id));
        boolean removeGoodsAttrs = iSpGoodsAttrService.remove(new QueryWrapper<SpGoodsAttr>().lambda().eq(SpGoodsAttr::getGoodsId, id));
        if (removeGoods && removeGoodsPics && removeGoodsAttrs) {
            LOGGER.info("deleteGoods success: id={}", id);
            return CommonResult.success(true);
        } else {
            LOGGER.info("deleteGoods failed: id={}", id);
            return CommonResult.failed("操作失败");
        }
    }

    @ApiOperation("修改商品是否促销")
    @RequestMapping(value = "/isPromote/{id}&{status}", method = RequestMethod.PUT)
    @ResponseBody
    public CommonResult<Boolean> updateIsPromote(@PathVariable("id") Integer id, @PathVariable("status") Boolean status) {
        SpGoods spGoods = new SpGoods();
        spGoods.setIsPromote(status);
        boolean update = iSpGoodsService.update(spGoods, new QueryWrapper<SpGoods>().eq("goods_id", id));
        if (update) {
            LOGGER.info("updateIsPromote success: id={}", id);
            return CommonResult.success(status);
        } else {
            LOGGER.info("updateIsPromote failed: id={}", id);
            return CommonResult.failed("修改失败");
        }
    }

    private void setGoodsCatIds(GoodsParam goodsParam, SpGoods spGoods) {
        for (int i = 0; i < goodsParam.getCatIds().length; i++) {
            switch (i) {
                case 0:
                    spGoods.setCatOneId(goodsParam.getCatIds()[i]);
                    break;
                case 1:
                    spGoods.setCatTwoId(goodsParam.getCatIds()[i]);
                    break;
                case 2:
                    spGoods.setCatThreeId(goodsParam.getCatIds()[i]);
                    break;
            }
        }
    }
}
